package com.heima.file.service.impl;

import com.heima.file.config.MinIOConfig;
import com.heima.file.config.MinIOConfigProperties;
import com.heima.file.service.FileStorageService;
import io.minio.GetObjectArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.RemoveObjectArgs;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Import;
import org.springframework.util.StringUtils;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

@Slf4j
@EnableConfigurationProperties(MinIOConfigProperties.class)
@Import(MinIOConfig.class)
@RequiredArgsConstructor
public class MinIOFileStorageService implements FileStorageService {

    private final MinioClient minioClient;

    private final MinIOConfigProperties minIOConfigProperties;

    private static final String SEPARATOR = "/";
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy/MM/dd");

    /**
     * 构建文件路径：dirPath/yyyy/MM/dd/filename
     */
    public String builderFilePath(String dirPath, String filename) {
        StringBuilder pathBuilder = new StringBuilder(50);
        if (StringUtils.hasText(dirPath)) {
            pathBuilder.append(dirPath).append(SEPARATOR);
        }
        pathBuilder.append(DATE_FORMAT.format(new Date())).append(SEPARATOR)
                .append(filename);
        return pathBuilder.toString();
    }

    /**
     * 通用文件上传
     */
    private String uploadFile(String prefix, String filename, InputStream inputStream, String contentType) {
        Objects.requireNonNull(filename, "文件名不能为空");
        Objects.requireNonNull(inputStream, "文件流不能为空");

        String filePath = builderFilePath(prefix, filename);
        try (InputStream in = inputStream) {
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .object(filePath)
                    .contentType(contentType)
                    .bucket(minIOConfigProperties.getBucket())
                    .stream(in, in.available(), -1)
                    .build();
            minioClient.putObject(putObjectArgs);
            return minIOConfigProperties.getReadPath() + SEPARATOR
                    + minIOConfigProperties.getBucket() + SEPARATOR + filePath;
        } catch (Exception ex) {
            log.error("上传文件失败: {}", filename, ex);
            throw new RuntimeException("上传文件失败", ex);
        }
    }

    @Override
    public String uploadImgFile(String prefix, String filename, InputStream inputStream) {
        return uploadFile(prefix, filename, inputStream, "image/jpeg");
    }

    @Override
    public String uploadHtmlFile(String prefix, String filename, InputStream inputStream) {
        return uploadFile(prefix, filename, inputStream, "text/html");
    }

    @Override
    public void delete(String pathUrl) {
        if (!StringUtils.hasText(pathUrl)) {
            return;
        }
        String key = pathUrl.replace(minIOConfigProperties.getEndpoint() + "/", "");
        int index = key.indexOf(SEPARATOR);
        if (index < 0) {
            log.warn("删除失败，路径格式不正确: {}", pathUrl);
            return;
        }
        String bucket = key.substring(0, index);
        String filePath = key.substring(index + 1);
        try {
            minioClient.removeObject(RemoveObjectArgs.builder()
                    .bucket(bucket)
                    .object(filePath)
                    .build());
        } catch (Exception e) {
            log.error("删除文件失败: {}", pathUrl, e);
        }
    }

    @Override
    public byte[] downLoadFile(String pathUrl) {
        if (!StringUtils.hasText(pathUrl)) {
            throw new IllegalArgumentException("文件路径不能为空");
        }
        String key = pathUrl.replace(minIOConfigProperties.getEndpoint() + "/", "");
        int index = key.indexOf(SEPARATOR);
        if (index < 0) {
            throw new IllegalArgumentException("路径格式不正确: " + pathUrl);
        }
        String bucket = key.substring(0, index);
        String filePath = key.substring(index + 1);

        try (InputStream inputStream = minioClient.getObject(
                GetObjectArgs.builder().bucket(bucket).object(filePath).build());
             ByteArrayOutputStream baos = new ByteArrayOutputStream()) {

            byte[] buff = new byte[1024];
            int rc;
            while ((rc = inputStream.read(buff)) != -1) {
                baos.write(buff, 0, rc);
            }
            return baos.toByteArray();
        } catch (Exception e) {
            log.error("下载文件失败: {}", pathUrl, e);
            throw new RuntimeException("下载文件失败", e);
        }
    }
}
